/**
 * 主题 Redux Reducer
 */

import {
  THEME_LOAD_START,
  THEME_LOAD_SUCCESS,
  THEME_LOAD_FAILURE,
  THEME_SET_CONFIG,
  THEME_UPDATE_CONFIG,
  THEME_RESET,
  THEME_CLEAR_ERROR,
} from './reduxType';

// 初始状态
const initialState = {
  config: null,
  loading: false,
  error: null,
  initialized: false,
  lastUpdated: null,
};

// Reducer
const themeReducer = (state = initialState, action) => {
  switch (action.type) {
    case THEME_LOAD_START:
      return {
        ...state,
        loading: true,
        error: null,
      };

    case THEME_LOAD_SUCCESS:
      return {
        ...state,
        loading: false,
        config: action.payload.config,
        lastUpdated: action.payload.timestamp,
        initialized: true,
        error: null,
      };

    case THEME_LOAD_FAILURE:
      return {
        ...state,
        loading: false,
        error: action.payload,
        initialized: true, // 即使失败也标记为已初始化
      };

    case THEME_SET_CONFIG:
      return {
        ...state,
        config: action.payload,
        lastUpdated: Date.now(),
      };

    case THEME_UPDATE_CONFIG:
      return {
        ...state,
        config: state.config ? {
          ...state.config,
          ...action.payload,
        } : action.payload,
        lastUpdated: Date.now(),
      };

    case THEME_RESET:
      return {
        ...initialState,
      };

    case THEME_CLEAR_ERROR:
      return {
        ...state,
        error: null,
      };

    default:
      return state;
  }
};

export default themeReducer;

